package com.angle.im.server.controller;

import com.angle.im.common.domain.enums.Platform;
import com.angle.im.common.utils.MessageModel;
import com.angle.im.server.service.MessageService;
import com.angle.im.server.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhangwei
 * @date 2019/4/15 16:27
 * @desc
 */
@RestController
@RequestMapping("auth")
public class ImController {

    @Autowired
    private MessageService messageService;

    /**
     * token校验流程:
     * 1. client请求对应业务服务
     * 2. 业务服务请求IM系统,获取token
     * 3. IM系统保存token,并根据业务传过来的有效时间设置token有效期
     * 4. 将token返回给客户端
     * 2. client根据token连接服务
     */
    @PutMapping("token")
    public MessageModel token(@RequestParam(defaultValue = "MUSIC_CP") Platform platform, @RequestParam String userId) {
        //生成临时token  不绑定用户到服务器,在用户实际连接时再绑定
        String token = JWTUtils.getInstance().getToken(platform.name(), userId, 60 * 24);
        return new MessageModel<>(10000, "", token);
    }

    /**
     * 向单个用户发送消息
     *
     * @param to   用户id
     * @param msg  消息
     * @param save 是否需要保存,默认否
     * @return
     */
    @PostMapping("sendOne")
    public MessageModel sendOne(@RequestHeader String token, @RequestParam String to, @RequestParam String msg, @RequestParam(defaultValue = "false") boolean save) {
        try {
            Claims claims = JWTUtils.getInstance().getClaims(token);
            String from = claims.getSubject();
            String platform = claims.get(JWTUtils.PLATFORM, String.class);
            boolean result = messageService.sendOne(platform, from, to, msg, save);
            return new MessageModel<>(10000, "", result);
        } catch (Exception e) {
            e.printStackTrace();
            return new MessageModel<>(10000, "", false);
        }
    }

    /**
     * 向用户列表发送消息
     *
     * @param toList 用户id列表
     * @param msg    消息
     * @param save   是否需要保存,默认否
     * @return
     */
    @PostMapping("sendList")
    public MessageModel sendList(@RequestHeader String token, @RequestParam List<String> toList, @RequestParam String msg, @RequestParam(defaultValue = "false") boolean save) {
        try {
            Claims claims = JWTUtils.getInstance().getClaims(token);
            String from = claims.getSubject();
            String platform = claims.get(JWTUtils.PLATFORM, String.class);
            boolean result = messageService.sendList(platform, from, toList, msg, save);
            return new MessageModel<>(10000, "", result);
        } catch (Exception e) {
            e.printStackTrace();
            return new MessageModel<>(10000, "", false);
        }
    }
}
